/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PluginPanel.java
 *
 * Created on 2010-8-14, 9:45:42
 */
package com.hyk.proxy.framework.shell.gui;

import com.hyk.proxy.framework.appdata.AppData;
import com.hyk.proxy.framework.common.Misc;
import com.hyk.proxy.framework.plugin.PluginManager;
import com.hyk.proxy.framework.plugin.PluginManager.InstalledPlugin;
import com.hyk.proxy.framework.update.ProductReleaseDetail.PluginReleaseDetail;
import com.hyk.proxy.framework.util.CommonUtil;
import com.hyk.proxy.framework.util.ImageUtil;
import com.hyk.proxy.framework.util.SwingHelper;
import com.hyk.util.io.FileUtil;
import com.hyk.util.net.NetUtil;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author wqy
 */
public class AvalablePluginPanel extends javax.swing.JPanel {

    /** Creates new form PluginPanel */
    public AvalablePluginPanel(MainFrame owner, PluginReleaseDetail plugin) {
        this.plugin = plugin;
        this.owner = owner;
        initComponents();
        setButtonsVisible(false);
        allPluginPanels.add(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        installButton = new javax.swing.JButton();
        iconLabel = new javax.swing.JLabel();
        descLabel = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createTitledBorder((plugin.name + " " + plugin.version)));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });

        installButton.setIcon(ImageUtil.INSTALL);
        installButton.setText("Install");
        installButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                installButtonActionPerformed(evt);
            }
        });

        iconLabel.setIcon(ImageUtil.PLUGIN32);

        descLabel.setText(plugin.desc);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(iconLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(installButton, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(descLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(descLabel)
                        .addGap(18, 18, 18)
                        .addComponent(installButton))
                    .addComponent(iconLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        setButtonsVisible(true);
        for (AvalablePluginPanel other : allPluginPanels) {
            if (other != this) {
                other.setButtonsVisible(false);
            }
        }

    }//GEN-LAST:event_formMouseClicked

    private void installButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_installButtonActionPerformed
        Misc.getGlobalThreadPool().submit(new Runnable() {
            public void run() {
                try {
                    installButton.setEnabled(false);
                    Future<Boolean> future = Misc.getGlobalThreadPool().submit(new Callable<Boolean>() {
                        public Boolean call() throws Exception {
                            try {
                                PluginManager pm = PluginManager.getInstance();
                                File pluginhome = null;
                                if (FileUtil.canWrite(AppData.getPluginsHome())) {
                                    pluginhome = AppData.getPluginsHome();
                                } else {
                                    pluginhome = AppData.getUserPluginsHome();
                                }
                                File downloadFile = CommonUtil.downloadFile(plugin.url, pluginhome);
                                if (null == downloadFile) {
                                    return Boolean.FALSE;
                                }
                                InstalledPlugin plugin = pm.loadPlugin(downloadFile, owner.trace);
                                pm.activatePlugin(plugin, owner.trace);
                                return Boolean.TRUE;
                            } catch (Exception ex) {
                                logger.error("Failed to install plugin:" + plugin, ex);
                            }
                            return Boolean.FALSE;
                        }
                    });
                    SwingHelper.showBusyButton(future, installButton, "Downloading...");
                    //installButton.setVisible(false);
                    //installButton.setEnabled(false);
                    try {
                        if (!future.get()) {
                            descLabel.setText("Failed to install plugin:" + plugin.name);
                        } else {
                            descLabel.setText(plugin.name + " has been installed!");
                        }
                    } catch (Exception e) {
                        logger.error("", e);
                    }
                } finally {
                    
                }
            }
        });

    }//GEN-LAST:event_installButtonActionPerformed

    private void setButtonsVisible(boolean isVisible) {
        installButton.setVisible(isVisible);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel descLabel;
    private javax.swing.JLabel iconLabel;
    private javax.swing.JButton installButton;
    // End of variables declaration//GEN-END:variables
    private PluginReleaseDetail plugin;
    private MainFrame owner;
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private static List<AvalablePluginPanel> allPluginPanels = new ArrayList<AvalablePluginPanel>();
}
